package com.lyl.mp.mybatisplus.config;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @ClassName CustomIdGenerator
 * @DESCRIPTION mybatis主键id自定义配置
 * @Author lvxiaobu
 * @Date 2023/2/22 14:04
 **/
@Slf4j
public class CustomIdGenerator implements IdentifierGenerator {

    private final AtomicLong al = new AtomicLong(1);

    @Override
    public Number nextId(Object entity) {
        //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
        String bizKey = entity.getClass().getName();
        log.info("bizKey:{}", bizKey);
        MetaObject metaObject = SystemMetaObject.forObject(entity);
        String name = (String) metaObject.getValue("name");
        final long id = al.getAndAdd(1);
        log.info("为{}生成主键值->:{}", name, id);
        return id;
    }

    @Override
    public String nextUUID(Object entity) {
        log.info("自定义为生成主键值");
        return UUID.randomUUID().toString();
    }
}
